#include "jitemcontainer.h"
#include <QAbstractItemView>
#include <QVBoxLayout>
#include <QPointer>
#include <QLabel>
#include <QTimer>
#include <QEvent>

namespace QTE
{

typedef JItemContainer::MsgLabelMode  MsgLabelMode;

class Q_DECL_HIDDEN JItemContainerPrivate : public QObject
{
public:
	JItemContainerPrivate(JItemContainer *q_ptr, QAbstractItemView *itemView);

protected:
	bool eventFilter(QObject *watched, QEvent *event) override;

public:
	JItemContainer *q_ptr;
	QPointer<QAbstractItemView> m_itemView;
	QLabel *m_msgLabel;
	MsgLabelMode m_msgLabelMode = JItemContainer::AlwayHide;
};

JItemContainerPrivate::JItemContainerPrivate(JItemContainer *q_ptr, QAbstractItemView *itemView) :
	q_ptr(q_ptr),
	m_itemView(itemView),
	m_msgLabel(new QLabel("No content", itemView))
{
	m_msgLabel->setObjectName("msgLabel");
	m_msgLabel->setAlignment(Qt::AlignCenter);
	m_msgLabel->setFrameShape(QFrame::NoFrame);
	m_msgLabel->setStyleSheet("background-color: rgba(0, 0, 0, 0); border: none;");

	m_msgLabel->hide();
}

bool JItemContainerPrivate::eventFilter(QObject *watched, QEvent *event)
{
	if( watched == m_itemView and event->type() == QEvent::Paint )
	{
		if( q_ptr->messageLabelMode() == q_ptr->Auto )
			q_ptr->messageLabel()->setVisible(m_itemView->model()->rowCount() == 0);
	}
	return false;
}

/*----------------------------------------------------------------------------------------------------*/

JItemContainer::JItemContainer(QAbstractItemView *itemView) :
	JScrollAreaUVLMEngine(itemView),
	d_ptr(new JItemContainerPrivate(this, itemView))
{
	auto verticalLayout = new QVBoxLayout(itemView);

	verticalLayout->setContentsMargins(0, 0, 0, 0);
	verticalLayout->addWidget(d_ptr->m_msgLabel);

	QTimer::singleShot(1, [this, itemView]()
	{
		itemView->setAutoScroll(false);
		itemView->installEventFilter(d_ptr);
	});
}

JItemContainer::~JItemContainer()
{
	delete d_ptr;
}

void JItemContainer::setMessageLabelMode(MsgLabelMode mode)
{
	d_ptr->m_msgLabelMode = mode;

	if( mode == AlwayShow )
		d_ptr->m_msgLabel->show();

	else if( mode == AlwayHide )
		d_ptr->m_msgLabel->hide();
}

void JItemContainer::setMessageLabel(QLabel *label)
{
	auto parent = d_ptr->m_msgLabel->parentWidget();
	delete d_ptr->m_msgLabel;

	d_ptr->m_msgLabel = label;
	label->setParent(parent);
}

MsgLabelMode JItemContainer::messageLabelMode() const
{
	return d_ptr->m_msgLabelMode;
}

const QLabel *JItemContainer::messageLabel() const
{
	return d_ptr->m_msgLabel;
}

QLabel *JItemContainer::messageLabel()
{
    return d_ptr->m_msgLabel;
}

} //namespace QTE
